package com.guit.hrms.controller;

import com.guit.hrms.dto.LoginDTO;
import com.guit.hrms.po.Employee;
import com.guit.hrms.po.WeChatSession;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.LoginService;
import com.guit.hrms.service.TokenService;
import com.guit.hrms.utils.AESUtil;
import com.guit.hrms.utils.JwtUtil;
import com.guit.hrms.utils.ThreadLocalUtil;
import com.guit.hrms.websocket.MessageWebSocketHandler;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/login")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     * @param employeeId 员工号
     * @param password 密码
     * @return 结果与员工信息
     */
    @PostMapping
    public Result loginUser(String employeeId, String password) {
        Employee employee = loginService.login(employeeId, password);
        if (employee == null) {
            return Result.error("用户名或密码错误");
        } else {
            //登录成功，生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("employeeId", employee.getEmployeeId());
            claims.put("username", employee.getUsername());
            claims.put("department",employee.getDepartment());
            claims.put("deptType",employee.getDeptType());
            if (employee.getOpenId() != null){
                claims.put("openId",employee.getOpenId());
            }
            String token = JwtUtil.genToken(claims);
            // 保存新token并获取旧token
            String oldToken = tokenService.saveToken(employee.getEmployeeId(), token);

            // 如果有旧token且不等于新token，通知旧会话已被踢出
            if (oldToken != null && !oldToken.equals(token)) {
                MessageWebSocketHandler.sendToUser(employee.getEmployeeId(),
                        "{\"type\":\"logout\",\"message\":\"您的账号已在其他设备登录，您已被迫下线\"}");
            }
            return Result.success(token);
        }
    }

    /**
     * 微信登录
     * @param loginDTO 登录信息
     * @return 结果与员工信息
     */
    @PostMapping("/wx")
    @Validated
    public Result loginUser(@Valid @RequestBody LoginDTO loginDTO) {
        WeChatSession session = loginService.getWeChatSession(loginDTO.getWxCode());
        if (session != null && session.getOpenid() != null) {
            String openId = null;
            try {
                openId = AESUtil.encrypt(session.getOpenid());
            } catch (Exception e) {
                throw new RuntimeException("openId 加密出错");
            }
            //微信登录成功，查询数据库，判断用户是否存在
            Employee employee = loginService.wxLogin(loginDTO.getEmployeeId(), loginDTO.getPassword(), openId);
            if (employee == null) {
                return Result.error("用户名、密码或微信号错误");
            } else {
                if (employee.getOpenId() == null) {
                    //微信绑定
                    Integer result = loginService.bindWeChat(employee.getEmployeeId(), openId);
                    if (result == 0) {
                        return Result.error("微信绑定失败");
                    }
                }
                //登录成功，生成token
                Map<String, Object> claims = new HashMap<>();
                claims.put("employeeId", employee.getEmployeeId());
                claims.put("username", employee.getUsername());
                claims.put("department",employee.getDepartment());
                claims.put("deptType",employee.getDeptType());
                claims.put("openId",session.getOpenid());
                String token = JwtUtil.genToken(claims);

                // 保存新token并获取旧token
                String oldToken = tokenService.saveToken(employee.getEmployeeId(), token);

                // 如果有旧token且不等于新token，通知旧会话已被踢出
                if (oldToken != null && !oldToken.equals(token)) {
                    MessageWebSocketHandler.sendToUser(employee.getEmployeeId(),
                            "{\"type\":\"logout\",\"message\":\"您的账号已在其他设备登录，您已被迫下线\"}");
                }
                return Result.success(token);
            }
        } else {
            return Result.error("微信登录失败"+ (session == null ? "!" : ": "+session.getErrmsg()));
        }
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result logout() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String employeeId = claims.get("employeeId").toString();
        tokenService.removeToken(employeeId);
        return Result.success();
    }
}
